

import { useState } from 'react';
import { message } from 'antd';
import { Room, RoomsResponse } from '../types/Room';
import { api, ApiError } from '../utils/api';
import { API_ENDPOINTS, MESSAGES } from '../constants/api';

export const useRooms = () => {
  const [rooms, setRooms] = useState<Room[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    page: 1,
    pageSize: 30,
    total: 0,
    totalPages: 0,
  });

  // 获取房间列表
  const fetchRooms = async (page: number = pagination.page, pageSize: number = pagination.pageSize) => {
    setLoading(true);
    try {
      const query = new URLSearchParams({ page: String(page), limit: String(pageSize) }).toString();
      const data = await api.get<RoomsResponse>(`${API_ENDPOINTS.ROOMS}?${query}`);
      const roomsData = data.data?.rooms || [];
      const pageInfo = data.data?.pagination;
      setRooms(prevRooms => {
        const prevMap = new Map(prevRooms.map(room => [room.id, room]));
        return roomsData.map(room => {
          const prev = prevMap.get(room.id);
          return {
            ...room,
            liveStatus: room.liveStatus ?? prev?.liveStatus,
            refreshing: false,
          };
        });
      });
      if (pageInfo) {
        setPagination({
          page: pageInfo.page,
          pageSize: pageInfo.limit,
          total: pageInfo.total,
          totalPages: pageInfo.totalPages,
        });
      } else {
        setPagination(prev => ({ ...prev, page, pageSize }));
      }

    } catch (error) {
      if (error instanceof ApiError) {
        message.error(`${MESSAGES.ERROR.FETCH_ROOMS}: ${error.message}`);
      } else {
        message.error(MESSAGES.ERROR.NETWORK);
      }
    } finally {
      setLoading(false);
    }
  };

  // 更新单个房间直播状态
  const updateSingleRoomStatus = async (roomId: string) => {
    // 设置该房间为刷新中状态
    setRooms(prevRooms => 
      prevRooms.map(room => 
        room.id === roomId ? { ...room, refreshing: true } : room
      )
    );

    try {
      const response = await fetch(`/api/dycast/getLiveInfo?roomId=${roomId}`);
      if (response.ok) {
        const result = await response.json();
        if (result.success && result.data) {
          // 更新该房间的状态
          setRooms(prevRooms => 
            prevRooms.map(room => 
              room.id === roomId 
                ? { ...room, liveStatus: result.data.status, refreshing: false }
                : room
            )
          );
          return;
        }
      }
      // 如果获取失败，设置为已结束状态
      setRooms(prevRooms => 
        prevRooms.map(room => 
          room.id === roomId 
            ? { ...room, liveStatus: 0, refreshing: false }
            : room
        )
      );
    } catch (error) {
      console.warn(`获取房间 ${roomId} 直播状态失败:`, error);
      // 如果获取失败，设置为已结束状态
      setRooms(prevRooms => 
        prevRooms.map(room => 
          room.id === roomId 
            ? { ...room, liveStatus: 0, refreshing: false }
            : room
        )
      );
    }
  };

  // 批量更新所有房间直播状态
  const updateLiveStatus = async (roomsData: Room[]) => {
    // 逐个更新房间状态
    for (const room of roomsData) {
      await updateSingleRoomStatus(room.id);
    }
  };

  // 创建房间
  const createRoom = async (values: any) => {
    try {
      await api.post(API_ENDPOINTS.ROOMS, values);
      message.success(MESSAGES.SUCCESS.CREATE);
      await fetchRooms(1, pagination.pageSize);
      return true;
    } catch (error) {
      if (error instanceof ApiError) {
        message.error(`${MESSAGES.ERROR.CREATE}: ${error.message}`);
      } else {
        message.error(MESSAGES.ERROR.NETWORK);
      }
      return false;
    }
  };

  // 更新房间
  const updateRoom = async (id: string, values: any) => {
    try {
      await api.put(API_ENDPOINTS.ROOM_BY_ID(id), values);
      message.success(MESSAGES.SUCCESS.UPDATE);
      await fetchRooms(pagination.page, pagination.pageSize);
      return true;
    } catch (error) {
      if (error instanceof ApiError) {
        message.error(`${MESSAGES.ERROR.UPDATE}: ${error.message}`);
      } else {
        message.error(MESSAGES.ERROR.NETWORK);
      }
      return false;
    }
  };

  // 删除房间
  const deleteRoom = async (id: string) => {
    try {
      await api.delete(API_ENDPOINTS.ROOM_BY_ID(id));
      message.success(MESSAGES.SUCCESS.DELETE);
      // 删除后保持当前页，如遇页数越界可在此调整
      await fetchRooms(pagination.page, pagination.pageSize);
      return true;
    } catch (error) {
      if (error instanceof ApiError) {
        message.error(`${MESSAGES.ERROR.DELETE}: ${error.message}`);
      } else {
        message.error(MESSAGES.ERROR.NETWORK);
      }
      return false;
    }
  };

  return {
    rooms,
    loading,
    fetchRooms,
    pagination,
    updateLiveStatus,
    updateSingleRoomStatus,
    createRoom,
    updateRoom,
    deleteRoom,
  };
};
